package com.situ.mall.controller;

import com.situ.common.util.PageResult;
import com.situ.common.util.Result;
import com.situ.mall.constant.RedisConstants;
import com.situ.mall.pojo.entity.User;
import com.situ.mall.pojo.query.UserQuery;
import com.situ.mall.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/list")
    private PageResult list(UserQuery userQuery) {
        PageResult pageInfo = userService.list(userQuery);
        return pageInfo;
    }
    @RequestMapping("/updateStatus")
    @ResponseBody
    public Result updateStatus(User user) {
        userService.update(user);
        return Result.ok("修改成功！");
    }
    @RequestMapping("/updateIsDeleted")
    @ResponseBody
    public Result updateIsDeleted(User user) {
        userService.update(user);
        return Result.ok("修改成功！");
    }
    @RequestMapping("/add")
    @ResponseBody
    public Result add(User user) {
        Integer accountCount = userService.selectByAccount(user);
        if (accountCount == 0) {
            userService.add(user);
            //将Product中真正使用的图片保存到Redis中
            redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, user.getImage());
            return Result.ok("添加成功！");
        } else {
            return Result.error("账号已经存在！");
        }

    }
    @RequestMapping("/selectById")
    @ResponseBody
    public Result selectById(Integer id) {
        User user = userService.selectById(id);
        return Result.ok(user);
    }
    @RequestMapping("/update")
    @ResponseBody
    public Result update(User user) {
        Integer accountCount = userService.selectByAccountId(user);
        if (accountCount == 0) {
            userService.update(user);
            redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, user.getImage());
            return Result.ok("修改成功！");
        } else {
            return Result.error("账号已经存在！");
        }

    }
    @RequestMapping("/deleteAll")
    @ResponseBody
    public Result deleteAll(Integer[] ids) {
        userService.deleteAll(ids);
        return Result.ok("删除成功！");
    }
    @RequestMapping("/deleteById")
    @ResponseBody
    public Result deleteById(Integer id) {
        userService.deleteById(id);
        return Result.ok("删除成功！");
    }
}
